<template>
    <!-- 抽屉 -->
    <a-drawer
    :width="720"
    :open="open"
    :body-style="{ paddingBottom: '80px' }"
    :footer-style="{ textAlign: 'right' }"
    @close="onClose"
  >
    <a-form :model="form" :rules="rules" layout="vertical" ref="formRef">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="角色名" name="roleName">
            <a-input v-model:value="form.roleName" placeholder="Please enter a role name" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="角色描述" name="description">
            <a-textarea
              v-model:value="form.description"
              :rows="4"
              placeholder="please enter url description"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template #extra>
      <a-space>
        <a-button @click="onClose">返回</a-button>
        <a-button type="primary" @click="onSubmit">提交</a-button>
      </a-space>
    </template>
  </a-drawer>

            <div class="app">
        <div class="top">
            <div class="input-container">
                <a-input-search v-model:value="value" placeholder="请输入要查找的角色名称" style="width: 300px" @search="onSearch"/>
            </div>
            <div class="buttons" style="margin-right: 20px;">
                <a-button type="primary" @click="formAdd">新增角色</a-button>      
            </div>
        </div>
        <div class="bottom">
            <div>
                <div class="role-actions">
                    <div>
                        <label for="" style="font-size: 17px;margin-left: 18px;">角色列表</label>
                    </div> 
                </div>
                <div>
                </div>
            </div>
            <div>
                <table>
                    <thead>
                        <tr>
                            <th>角色名称</th>
                            <th>状态</th>
                            <th>角色描述</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in items" :key="index">
                            <td>{{ item.roleName }}</td>
                            <td>
                                <a-space direction="vertical">
                                    <a-switch v-model:checked="item.isActived" @change="updateStatus(item)" checked-children="启用"
                                        un-checked-children="停用" />
                                </a-space>
                            </td>
                            <td>{{ item.description }}</td>
                            <td>

                                <a href="#">
                                    <FormOutlined class="formoutlinedicon" @click="() => formEdit(item)"/>
                                </a>
                                <a-divider type="vertical" />
                                <a-popconfirm title="确定要删除吗？" ok-text="确定" cancel-text="取消"
                                    @confirm="handleDelete(item)">
                                    <a href="#">
                                        <DeleteOutlined class="deleteicon" />                                        
                                    </a>
                                </a-popconfirm>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div>

            </div>
        </div>
    </div>
</template>

<script setup>
import { ref,watch  } from 'vue';
import { reactive,onMounted } from 'vue';
import { FormOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import request from '../store/request';

//初始数据渲染
const items =reactive([]);
onMounted(async()=>{
    const response = await request.get('http://localhost:5133/api/GetRoleAllPage?page=1&pageSize=100');
    // console.log(response);
    response.data.data.forEach(res => {
        console.log(res);
        items.push(res)
    });
})

// 控制状态按钮选项
const updateStatus = async(item)=>{
    try {
        // console.log(item.isActived);
        const response = await request.put(`http://localhost:5133/api/EnableRole/${item.id}`,{
            id:item.id,
            isActived:item.isActived
        })
        // console.log(response);
    } catch (error) {
        console.error('更新失败');
    }
}

// 定义表单引用
const formRef = ref(null);
//模态框数据定义
const form = reactive({
    id:'',
    roleName: '',
    description: ''
});
//自定义校对
const rules = {
    roleName: [
    {
      required: true,
      message: '请输入角色名称!',
    },
  ],
  description: [
    {
      required: true,
      message: '请输入角色描述!!',
    },
  ],
};
const open = ref(false);
//新增按钮,跳出模态框
const formAdd = () => {
  open.value = true;
  form.id = "";
    form.roleName ="";
    form.description = "";
};
//返回按钮,关闭模态框
const onClose = () => {
  open.value = false;
};
//编辑按钮,跳出模态框
const formEdit = (item)=>{
    open.value = true;    
    form.id = item.id;
    form.roleName = item.roleName;
    form.description = item.description;
}
//提交按钮
const onSubmit = async()=>{
    try {
        //自主验证表单
        await formRef.value.validate();

        if(form.id){
            await request.put(`http://localhost:5133/api/UpdateRole/${form.id}`,form).then(res=>{
                var res =  res.data.data
                //更新渲染数据
                var index =  items.findIndex(item=>item.id == res.id)
                items[index].roleName = res.roleName
                items[index].description = res.description 
            });
        }else{
            await request.post('http://localhost:5133/api/AddRole',form).then(res=>{
               //更新渲染数据
                items.push(res.data.data)
            });
        }

        open.value = false;
        
    } catch (error) {
        console.error('Error saving role:', error);
    }
}
//状态按钮
const state = reactive({
    checked1: true,
});

const status = ref('');


//确认删除方法
const handleDelete = async(item) => {
    const id = item.id
    console.log(item);
    const response = await request.delete(`http://localhost:5133/api/DeleteRole/${id}`);
    var index =  items.indexOf(item)
    items.splice(index,1)
};
//查找方法
const value = ref(''); 
const onSearch = async()=>{
    const searchValue = value.value;
    console.log(searchValue);
    
    //过滤出符合条件的角色
    const filteredRole = items.filter(role=>role.roleName.includes(searchValue));
    // 过滤出符合条件的角色de的id
    const confirmRoleid  = filteredRole.map(role=>role.id);
    console.log(confirmRoleid);
    // 向后端发送请求
    const response = await request.get(`http://localhost:5133/api/RoleGetById/${confirmRoleid}`);
    console.log(response);
    //数据渲染
    items.splice(0);
    items.push(response.data.data)
    }
//监听搜索输入框，当输入框文本为空时，自动渲染全部数据
watch(value, async (newValue) => {
            if (newValue === "") {
                try {
                    
                    const response = await request.get('http://localhost:5133/api/GetRoleAllPage?page=1&pageSize=100');
                    if (Array.isArray(response.data.data)) {
                        items.splice(0);
                        items.push(...response.data.data);
                    } else {
                        console.error('Data received is not an array');
                    }
                } catch (error) {
                    console.error('Error fetching all roles:', error);
                }
            }
        });
</script>

<style scoped>
.app {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.top {
    display: flex;
    align-items: center;
}

.input-container {
    display: flex;
    align-items: center;
    flex-grow: 1;
    margin-right: 20px;
}

.fixed-width-label {
    width: 80px;
    text-align: right;
    margin-right: 5px;
}

.flexible-input {
    flex-grow: 1;
}

.role-name,
.buttons {
    flex: 1;
    display: flex;
    align-items: center;
}

.role-name {
    margin-left: 70px;
    margin-right: 50px;
}

.buttons {
    justify-content: flex-end;
    margin-right: 20px;
}

.formoutlinedicon{
    color: rgb(36, 35, 35);
}
.formoutlinedicon:hover {
    color: rgb(43, 123, 235);
}


select option[value=""] {
    color: gray;
}
.deleteicon {
    color: rgb(36, 35, 35);
}

.deleteicon:hover {
    color: rgb(247, 0, 41);
}

.role-actions {
    display: flex;
    align-items: center;
}

.role-actions>div:first-child {
    margin-right: 20px;
}

.bottom {
    background-color: #fff;
    margin-top: 20px;
    border-radius: 4px;
}

.add-role {
    background-color: rgb(9, 96, 189);
    color: white;
    border: none;
    width: 85px;
    height: 35px;
    border-radius: 8px;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 8px;
}

th,
td {
    border: 1px solid rgb(240, 240, 240);
    padding: 8px;
    text-align: center;
    vertical-align: middle;
}

</style>